import { useLocaleStoreWithOut } from '@/store/modules/locale';
import type { App } from 'vue';
import { createI18n } from 'vue-i18n';
import type { I18nOptions } from 'vue-i18n';
export const setHtmlPageLang = (locale: LocaleType) => document.documentElement.setAttribute('lang', locale);

export let i18n: ReturnType<typeof createI18n>;

const createI18nOptions = async (): Promise<I18nOptions> => {
  const localeStore = useLocaleStoreWithOut();
  const lang = localeStore.lang;
  const localeMap = localeStore.localeMap;
  const defaultLocale = await import(`@/locales/${lang}.yaml`);

  const message = defaultLocale.default;
  // 写html lang属性
  setHtmlPageLang(lang);
  localeStore.setCurrentLocale({ lang });
  return {
    legacy: false,
    locale: lang,
    fallbackLocale: lang,
    messages: {
      [lang]: message
    },
    availableLocales: localeMap.map((v) => v.lang),
    sync: true,
    silentTranslationWarn: true,
    missingWarn: false,
    silentFallbackWarn: true
  };
};
export const setupI18n = async (app: App<Element>) => {
  const options = await createI18nOptions();
  i18n = createI18n(options);
  app.use(i18n);
};
